package com.sandwich.api.controller.v1;

import com.sandwich.admin.apibean.CommentAddRequest;
import com.sandwich.admin.apibean.CommentInfo;
import com.sandwich.admin.apibean.CommentRequest;
import com.sandwich.admin.domain.CommentEntity;
import com.sandwich.admin.service.CommentService;
import com.sandwich.common.PageResponse;
import com.sandwich.common.SimpleResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description 评论信息
 * @date 2021-07-28
 */
@RestController("ApiCommentControllerV1")
@RequestMapping("/api/v1")
public class CommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 搜索
     *
     * @param request
     * @param headers
     * @param commentRequest
     * @return
     */
    @PostMapping("/query/comment")
    public ResponseEntity queryComment(HttpServletRequest request, @RequestHeader HttpHeaders headers,
                                       @RequestBody CommentRequest commentRequest) {
        Page<CommentEntity> commentEntityPage = commentService.queryCommentEntity(commentRequest);

        List<CommentEntity> contents = commentEntityPage.getContent();
        List<CommentInfo> commentInfos = contents.stream().map(x -> new CommentInfo(x)).collect(Collectors.toList());

        PageResponse pageResponse = new PageResponse();
        pageResponse.setTotalPage(commentEntityPage.getTotalPages());
        pageResponse.setContents(commentInfos);
        return new ResponseEntity(pageResponse, HttpStatus.OK);
    }

    /**
     * 添加评论
     *
     * @param request
     * @param headers
     * @param commentAddRequest
     * @return
     */
    @PostMapping("/comment")
    public ResponseEntity addComment(HttpServletRequest request, @RequestHeader HttpHeaders headers,
                                     @RequestBody CommentAddRequest commentAddRequest) {
        CommentEntity commentEntity = new CommentEntity();
        commentEntity.setPk(commentAddRequest.getPk());
        commentEntity.setComment(commentAddRequest.getComment());
        commentEntity.setParentPk(commentAddRequest.getParentPk());
        commentEntity.setContentSummaryPk(commentAddRequest.getContentSummaryPk());
        commentEntity.setUserPk(commentAddRequest.getUserPk());

        CommentEntity adEntity =commentService.addOrUpdateCommentEntity(commentEntity);
        CommentInfo commentInfo = new CommentInfo(adEntity);
        return new ResponseEntity(new SimpleResponse(Stream.of(commentInfo).collect(Collectors.toList())), HttpStatus.OK);
    }
}